package com.minxi.web.controller;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
@WebServlet(name = "JspServlet",urlPatterns = "/add")
public class JspServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse response) throws ServletException {
        String userName = req.getParameter("userName");
        String passWord = req.getParameter("userWord");
        String userPhone = req.getParameter("userPhone");
        String userSex = req.getParameter("userSex");
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            String url = "jdbc:mysql://localhost:3306/student?serverTimezone=Asia/Shnaghai";
            String user = "root";
            String pwd = "123456";
            connection = DriverManager.getConnection(url, user, pwd);
            String sql = "insert into user_info(user_name,user_pwd,user_phone,user_sex)values(????);";
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1, userName);
            preparedStatement.setString(2, passWord);
            preparedStatement.setString(3, userPhone);
            preparedStatement.setInt(4, Integer.parseInt(userSex));
            int rs = preparedStatement.executeUpdate();
            if (rs > 0) {
                response.sendRedirect("jsp/home.jsp");
            } else {
                response.sendRedirect("jsp/add.jsp");
            }

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                if (null !=preparedStatement){
                    preparedStatement.close();
                }if (null !=connection){
                    connection.close();
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }

    }

    }

